from cgitb import text
from datetime import datetime

from sqlalchemy import Column, Integer, String, CHAR, Float, desc

from models.base import db

class internet_source(db.Base):
    __tablename__ = 'internet_source'
    id = Column(Integer, primary_key=True, autoincrement=True)
    order_number = Column(String(30), nullable=False)
    sentence_index = Column(CHAR(8), nullable=False)
    original_content = Column(String(150), nullable=False)
    similar_content = Column(String(300), default='佚名')
    rate = Column(Float, default=0)
    source = Column(String(1000), default=0)
    title = Column(String(80), default=0)
    create_time = Column('create_time', Integer)

    def __init__(self):
        self.create_time = int(datetime.now().timestamp())

    @classmethod
    def get_sentence_index(cls, order_number):
        index = []
        result = db.execute(text('select DISTINCT(sentence_index) from internet_source where order_number = :order_number'),
                            {'order_number': order_number}).fetchall()
        for i in result:
            index.append(i[0])
        return index

    @classmethod
    def get_top_rate(cls, order_number, sentence_index):
        sentences = db.query(cls).filter_by(order_number=order_number, sentence_index=sentence_index).order_by(
            desc('rate')).limit(5).all()
        return sentences

